<script  lang="ts" setup>
import { getAddressInfo, getPinInfo } from "@/api/metaIO/index";
import UserImg from "@/assets/images/user.png";
import { msgPost } from "@/components/Post/index";
import { PostEdit } from "@/components/PostEdit";
import { router } from "@/router";
import { store } from "@/store";
import { userStore } from "@/store/modules/walletUser";
import * as metaidv2api from "@/utils/metaidv2api.js";
import metaidv2Utils from "@/utils/metaidv2Utils";
import { message } from "ant-design-vue";
import { computed, onMounted, ref, watch } from "vue";

// interface MsgList {
//   content: string;
//   name: string;
//   avatar: string;
//   time: string;
//   shortTxid: string;
//   metaid: string;
//   txid: string;
//   address: string;
//   id: string;
// }
const walletUser = userStore(store);
const isLogin = computed(() => walletUser.getIsLogin);
const userInfo: any = computed(() => walletUser.getUserInfoObj);

const props = defineProps<{
  pinInfo: any;
  isChild?: boolean;
  isComment?: boolean;
}>();

const emit = defineEmits(["showBuzzDetail"]);

const likesCount = ref(0);
const commentInfo: any = ref({});
const parentSummary: any = ref({});
const time = ref();
const content = ref();
const name = ref();
const imgUrl = ref();
const shortTxid = ref();
const txid = ref();
const metaid = ref();
const address = ref();
const id = ref();
const quotePinFlag = ref(false);
const showPostEdit = ref();
const isPayComment = ref(false);
const isPayForward = ref(false);
const quotePin = ref();
const followed = ref(false);

function toTxidInfo() {
  console.log("toTxidInfo", txid.value);
  // 前往https://www.mvcscan.space/tx/{txid}页面
  window.open(`https://www.mvcscan.space/tx/${txid.value}`);
}

function shortIdString(string: string, num: number) {
  // 保留字符串前n位后面省略
  return `${string.substring(0, num)}...`;
}
// function shortMetaIdString() {
//   // 保留字符串倒数第3、4位，其它省略
//   return `${props.metaid.substring(
//     props.metaid.length - 4,
//     props.metaid.length - 2
//   )}`;
// }

// 点赞
async function likeBuzz() {
  if (!props.isComment && props.isChild) {
    showBuzzDetail();
    return;
  }
  console.log("likeBuzz ***");
  const res = await window.$walletUtils.payLike(id.value);
  console.log("likeBuzz", res);
  if (res) {
  }
}

function showBuzzDetail(sid?: any) {
  if (!props.isComment && props.isChild) {
    showBuzzDetail();
    return;
  }
  emit("showBuzzDetail", sid || id.value);
}

function getAddressInfoFn(address) {
  return new Promise((resolve) => {
    getAddressInfo(address).then((res) => {
      console.log("getAddressInfo", res);
      resolve(res);
    });
  });
}

function getPinInfoFn(pinId) {
  return new Promise((resolve) => {
    getPinInfo(pinId).then((res) => {
      console.log("getPinInfo", res);
      resolve(res);
    });
  });
}

function commentBtnEvent() {
  isPayComment.value = true;
  isPayForward.value = false;
  quotePin.value = {
    id: id.value,
  };
  showPostEdit.value = true;
}

function repostBtnEvent() {
  isPayComment.value = false;
  isPayForward.value = true;
  quotePin.value = {
    id: id.value,
  };
  showPostEdit.value = true;
}

function closeEditEvent() {
  showPostEdit.value = false;
}

async function checkFollow() {
  console.log("checkFollow");
  if (userInfo.value.metaid) {
    //同一个人
    if (userInfo.value.metaid === metaid.value) {
      followed.value = true;
      return;
    }
    const followRecord: any = await metaidv2api.getFollowRecord(
      metaid.value,
      userInfo.value.metaid
    );
    //有code属性则表示没有找到记录
    if (followRecord?.data?.metaId) {
      followed.value = true;
    }
  }
}

async function followEvent() {
  if (!isLogin) {
    message.info("please login first");
    return;
  }
  const followRecord: any = await metaidv2api.getFollowRecord(
    metaid.value,
    userInfo.value.metaid
  );
  console.log("followRecord &*", followRecord);
  //有code属性则表示没有找到记录
  if (followRecord?.data?.metaId) {
    message.success("followed");
    return;
  }
  const res = await window.$walletUtils.following(metaid.value);
  if (res) {
    message.success("Operation successful");
  }
}

async function handlePinInfo() {
  const pinInfo = props.pinInfo;
  if (!pinInfo.contentSummary) {
    return;
  }
  const dataObj = JSON.parse(pinInfo.contentSummary);
  const date = new Date(pinInfo.timestamp * 1000);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  const info = (await getAddressInfoFn(pinInfo.address)) as {
    name: string;
    avatar: string;
    metaid: string;
  };
  time.value = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  content.value = dataObj.content;
  id.value = pinInfo.id;
  name.value = info.name;
  imgUrl.value = info.avatar;
  metaid.value = info.metaid;
  address.value = pinInfo.address;
  txid.value = pinInfo.txid;
  shortTxid.value = shortIdString(pinInfo.genesisTransaction, 8);
  likesCount.value = await metaidv2Utils.getBuzzLikeRefStatus(pinInfo.id);
  commentInfo.value = await metaidv2Utils.getBuzzCommentRefStatus(pinInfo.id);
  if (dataObj.quotePin) {
    quotePinFlag.value = true;
    parentSummary.value = await getPinInfoFn(dataObj.quotePin);
  }
  checkFollow();
  console.log("pinInfo ***** 11", pinInfo);
}

function toPerfile() {
  router.push({
    path: "/profile/" + address.value,
  });
}

// watch 监听props.pinInfo的变化
watch(
  () => props.pinInfo,
  async (newVal) => {
    if (newVal) {
      handlePinInfo();
    }
  }
);

onMounted(async () => {
  if (props.pinInfo) {
    handlePinInfo();
  }
});
</script>

<template>
  <div class="post-wrap">
    <div class="header">
      <div class="title">
        <img
          class="ava-img"
          @click.stop="toPerfile"
          :src="imgUrl ? 'https://man.metaid.io' + imgUrl : UserImg"
          alt=""
        />
        <div class="user-info">
          <div class="name" @click.stop="toPerfile">
            {{
              name || (address && "metaid-user-" + shortIdString(address, 6))
            }}
          </div>
          <div class="tool" v-if="!isChild && !followed">
            <div class="btn" @click="followEvent">Follow</div>
          </div>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="post-item">
        <!-- <div class="post-title">translate</div> -->
        <div class="post-content" @click="showBuzzDetail()">
          {{ content }}
        </div>
      </div>
      <div
        :style="!isComment ? 'cursor: pointer' : 'cursor: default'"
        @click.stop="!isComment && showBuzzDetail()"
      >
        <msgPost
          v-if="quotePinFlag"
          :pinInfo="parentSummary"
          :isChild="true"
          :isComment="isComment"
          style="margin-top: 20px; margin-bottom: 20px"
          @showBuzzDetail="showBuzzDetail"
        ></msgPost>
      </div>
      <!-- <div class="post-desc">
        <div class="left">
          <img class="type-img" src="@/assets/images/my.png" alt="" />
          <span style="cursor: pointer" @click="toTxidInfo">
            {{ shortTxid }}</span
          >
        </div>
      </div> -->
    </div>
    <div class="footer">
      <div class="right">{{ time }}</div>
      <div class="tool-item">
        <div class="item-icon">
          <div class="icon-img" title="like" @click="likeBuzz">
            <i class="iconfont icon-dianzan"></i
            >{{ likesCount > 0 ? likesCount : "" }}
          </div>
          <div class="icon-img" title="repost" @click="repostBtnEvent">
            <i class="iconfont icon-zhuanfa"></i>
          </div>
          <div class="icon-img" title="comment" @click="commentBtnEvent">
            <i class="iconfont icon-pinglun"></i>
            {{ commentInfo?.commentCount > 0 ? commentInfo?.commentCount : "" }}
          </div>
          <div class="icon-img" :title="shortTxid">
            <i class="iconfont icon-lianjie" @click="toTxidInfo"></i>
          </div>
        </div>
      </div>
    </div>
    <PostEdit
      v-show="showPostEdit"
      :isPayComment="isPayComment"
      :isPayForward="isPayForward"
      :quotePin="quotePin"
      @close="closeEditEvent"
    ></PostEdit>
  </div>
</template>

<style lang="less" scoped>
.post-wrap {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  background: #fff;
  border: 1px solid #f1f1f1;
  border-radius: 10px;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 20px;
    border-bottom: 1px solid #f1f1f1;

    .ava-img {
      width: 48px;
      height: 48px;
      margin-right: 10px;
      cursor: pointer;
      border-radius: 50%;
      object-fit: cover;
    }

    .title {
      display: flex;
      align-items: center;
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }

    .tool {
      display: flex;
      align-items: center;

      .btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 70px;
        height: 23px;
        font-size: 14px;
        color: #00b1ff;
        cursor: pointer;
        border: 1px solid #00b1ff;
        border-radius: 4px;
      }
    }
  }

  .content {
    padding: 20px;
    cursor: pointer;

    .post-item {
      .post-title {
        font-size: 16px;
        font-weight: bold;
        color: #333;
      }

      .post-content {
        font-size: 14px;
        color: #333;
      }
    }

    .post-desc {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 10px;

      .left {
        display: flex;
        align-items: center;
        color: #898a8c;

        .type-img {
          width: 20px;
          height: 20px;
          margin-right: 5px;
        }
      }

      .right {
        color: #898a8c;
      }
    }
  }

  .ava-span {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 48px;
    height: 48px;
    margin-right: 10px;
    color: #d7dde4;
    background: #2b3440;
    border-radius: 50%;
  }

  .user-info {
    .name {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      cursor: pointer;
    }

    .desc {
      font-size: 14px;
      color: #898a8c;
    }
  }

  .tool-item {
    .item-icon {
      display: flex;
      color: #333;
    }

    .icon-img {
      margin-right: 20px;
      cursor: pointer;

      i {
        font-size: 20px;
      }
    }
  }

  .footer {
    display: flex;
    justify-content: space-between;
    padding: 10px 20px;
    border-top: 1px solid #f1f1f1;
  }
}
</style>
